#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include "Log.hpp"
#include "translate.hpp"

extern Log logger;
Init init;

class Task
{
public:
    Task(int sockfd, const std::string &ip, const uint16_t &port)
        : _sockfd(sockfd), _clientip(ip), _clientport(port)
    {
    }

    void Run()
    {
        char buf[4096];
        ssize_t n = read(_sockfd, buf, sizeof(buf));
        if (n > 0)
        {
            buf[n] = 0;
            std::cout << "client key# " << buf << std::endl;

            // 把客户传来的单词调用翻译服务查询，
            std::string echo_string = init.translation(buf);

            /*
            sleep(5);           
            logger(Warrning,"close sockfd %d done",_sockfd);    //关闭文件描述符
            sleep(2);               //返回写给客户消息前休眠2秒 
            */
           
            // 给客户写回单词的翻译版
            ssize_t m = write(_sockfd, echo_string.c_str(), echo_string.size()); // 测试不存在的文件描述符
            if (m < 0)
            {
                logger(Warrning, "write error error: %d,errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0) // 客户端退出
        {
            logger(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
        }
        else
        {
            logger(Warrning, "%s:%d quit, server close sockfd: %d\n", _clientip.c_str(), _clientport, _sockfd);
        }
        close(_sockfd);
    }

    void operator()() // 仿函数
    {
        Run();
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};

